package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

import com.ruoyi.system.domain.SapData;
import com.ruoyi.system.domain.vo.SapDataRgblVo;
import com.ruoyi.system.https.bo.ZWS_PP_GET_PWOI_RESPONSE;
import com.ruoyi.system.https.vo.ZWS_PP_GET_PWOI_REQUEST;
import com.ruoyi.system.mapper.SapDataMapper;
import com.ruoyi.system.service.SapDataService;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tianfu-li
 * @since 2025-43-04
 */
@Service
public class SapDataServiceImpl extends ServiceImpl<SapDataMapper, SapData> implements SapDataService {
@Autowired
ExternalApiService externalApiService;
@Autowired
SapDataMapper sapDataMapper;
   @Value("${sap.ZMES_GET_PWOI.url}")
   private String ZMES_GET_PWOI_Url;
    @Value("${sap.ZMES_GET_PWOH.SOAPAction}")
    private String ZMES_GET_PWOI_SOAPAction;
    @Value("${sap.auth.user}")
    private String user;
    @Value("${sap.auth.password}")
    private String password;
    @Override
    public boolean updateSapDataBySap(String orderNo, String userId) throws JsonProcessingException {
        //查询表中已有该单号数据所有字段
        List<SapData> localSapData=selectByOrderNo(orderNo);
    //再通过ZWS_PP_GET_PWOI接口从 sap 获取数据;
    //组装body
    ZWS_PP_GET_PWOI_REQUEST.Item item=new ZWS_PP_GET_PWOI_REQUEST.Item();
    ZWS_PP_GET_PWOI_REQUEST.Pwoi pwoi=new ZWS_PP_GET_PWOI_REQUEST.Pwoi();
        pwoi.setItem(item);
    ZWS_PP_GET_PWOI_REQUEST.ZmesGetPwoi zmesGetPwoi=new ZWS_PP_GET_PWOI_REQUEST.ZmesGetPwoi();
        zmesGetPwoi.setOrderNo(orderNo);
        zmesGetPwoi.setPwoi(pwoi);
    ZWS_PP_GET_PWOI_REQUEST.SoapBody soapBody=new ZWS_PP_GET_PWOI_REQUEST.SoapBody();
        soapBody.setZmesGetPwoi(zmesGetPwoi);
    ZWS_PP_GET_PWOI_REQUEST zwsPpGetPwoiRequest=new ZWS_PP_GET_PWOI_REQUEST();
        zwsPpGetPwoiRequest.setBody(soapBody);
    //转成xml
    XmlMapper xmlMapper=new XmlMapper();
    ObjectWriter objectWriter=xmlMapper.writerWithDefaultPrettyPrinter();
    String xml = objectWriter.writeValueAsString(zwsPpGetPwoiRequest);
    //设置请求头的额外参数
    //添加SOAPAction
    Map<String,String> headerParamsMap=new HashMap<>();
        headerParamsMap.put("Content-Type", "text/xml;charset=UTF-8");
        headerParamsMap.put("Accept", "text/xml");
        headerParamsMap.put("User_Agent","Apache-HttpClient/4.5.5 (Java/17.0.12)");
        headerParamsMap.put("Accept_Encoding","gzip,deflate");
        headerParamsMap.put("Content_Length","1074");
        headerParamsMap.put("Host","s4suitedevapp.nipponpaint.com.sg:8200");
        headerParamsMap.put("Connection","Keep-Alive");
        if(StringUtils.isNotBlank(ZMES_GET_PWOI_SOAPAction)) {
        headerParamsMap.put("SOAPAction", ZMES_GET_PWOI_SOAPAction);
    }
    // 添加基本认证信息
        if (StringUtils.isNotBlank(user) && StringUtils.isNotBlank(password)) {
        String auth = user + ":" + password; // 替换为你的用户名和密码
        byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes(StandardCharsets.UTF_8));
        String authHeader = "Basic " + new String(encodedAuth);
        headerParamsMap.put("Authorization", authHeader);
    }
    //发送请求
    ZWS_PP_GET_PWOI_RESPONSE zws_pp_get_pwoi_response=externalApiService.callExternalApi(ZMES_GET_PWOI_Url, HttpMethod.POST, headerParamsMap,null,xml, ZWS_PP_GET_PWOI_RESPONSE.class);
        return dealResponse(localSapData ,zws_pp_get_pwoi_response);
}

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateBatchSapDataBySap(List<String> orderNos, String userId) throws JsonProcessingException {
        try {
            for (String orderNo:orderNos)  {
                updateSapDataBySap(orderNo,userId);
            }
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }

        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean dealResponse(List<SapData> localSapData ,ZWS_PP_GET_PWOI_RESPONSE zws_pp_get_pwoi_response){
        int flage=-1;
        if(zws_pp_get_pwoi_response==null){
            return false;
        }else {
            //接口返回结果映射为sapData对象
            List<SapData> sapDataList = ZWS_PP_GET_PWOI_RESPONSE.bodyToSapData(zws_pp_get_pwoi_response);
            //数据对比
            //数量对比
            if (localSapData.size() != sapDataList.size()) {
                //数量不一致，更新数据状态
                Set<Long> Ids = localSapData.stream().map(SapData::getId).collect(Collectors.toSet());
                if(Ids.size()>0) {
                    flage = updateSapDataStatusBatch(Ids, 0);
                }
                if (flage == -1||flage>0) {
                    //更新成功，插入新数据
                    insertSapDataBatch(sapDataList);
                    return true;
                } else {
                    return false;
                }
            } else {
                //数量一致，对比数据
                int[] flag = new int[sapDataList.size()];
                for (int i = 0; i < sapDataList.size(); i++) {
                    int k = 0;
                    for (int j = 0; j < localSapData.size(); j++) {
                        //确定同一条数据
                        //TODO 加batch判断
                        if (localSapData.get(i).getOrderNo().equals(sapDataList.get(j).getOrderNo())
                                && localSapData.get(i).getOperation().equals(sapDataList.get(j).getOperation())
                                && localSapData.get(i).getStep().equals(sapDataList.get(j).getStep())) {
                            flag[j] = 1;
                            //判断数据是否一致
                            if (localSapData.get(i).equals(sapDataList.get(j))) {
                                //数据一致，跳过
                                break;
                            } else {
                                //数据不一致，更新数据
                                localSapData.get(i).setIsEnable(0);
                                updateSapData(localSapData.get(i));
                                insertSapData(sapDataList.get(j));
//                                if(localSapData.get(i).getIsEnable()==0) {
//                                    sapDataList.get(j).setId(localSapData.get(i).getId());
//                                    updateSapData(sapDataList.get(j));
//                                }
                                break;

                            }

                        }
                        k++;
                    }
                    if (k == sapDataList.size()) {
                        //遍历完，没有找到，插入新数据
                        SapData sapData = sapDataList.get(i);
                        sapData.setIsEnable(1);
                        insertSapData(sapData);
                    }
                }
                for (int i = 0; i < flag.length; i++) {
                    if (flag[i] == 0) {
                        //本地数据存在，接口数据不存在。更新状态
                        localSapData.get(i).setIsEnable(0);
                        updateSapData(localSapData.get(i));
                    }
                }
            }
            return true;
        }
    }



    public List<SapData> selectByOrderNo(String orderNo) {
        /*LambdaQueryWrapper<SapData> wrapper = new LambdaQueryWrapper();
        wrapper.eq(SapData::getOrderNo, orderNo);
        wrapper.eq(SapData::getIsEnable,1);
        wrapper.orderByAsc(sapData -> {
            try {
                return Integer.parseInt(sapData.getStep());
            } catch (NumberFormatException e) {
                // 处理转换异常，例如返回一个默认值或抛出自定义异常
                return 0; // 默认值
            }
        });*/
        //return this.list(wrapper);
        List<SapData> sapDataList = sapDataMapper.selectByOrderNo(orderNo);

        return sapDataList;
    }
    //批量修改状态
    public int  updateSapDataStatusBatch(Set<Long> Ids ,Integer status) {
        LambdaUpdateWrapper<SapData> wrapper = new LambdaUpdateWrapper();
        wrapper.in(SapData::getId, Ids);
        wrapper.set(SapData::getIsEnable, status);//设置状态为0-已删除/旧数据
        return  baseMapper.update(new SapData(),wrapper);
    }
    //批量插入
    public boolean insertSapDataBatch(List<SapData> dataList) {
        return saveBatch(dataList);
    }
    public int insertSapData(SapData sapData) {
        return this.baseMapper.insert(sapData);
    }
    public int updateSapData(SapData sapData) {
        return this.baseMapper.updateById(sapData);
    }

    @Override
    public List<SapDataRgblVo> selectByOrderNos(List<String> orderNos) {
        return sapDataMapper.selectByOrderNos(orderNos);
    }
    @Override
    public List<SapDataRgblVo> selectByOrderNoVo(String orderNo) {
        return sapDataMapper.selectByOrderNoVo(orderNo);
    }
    @Override
    public List<SapDataRgblVo> selectByIdsVo(List<Long> Ids) {
        return sapDataMapper.selectByIdsVo(Ids);
    }
    @Override
    public List<SapData> selectByIds(List<Long> Ids) {
        LambdaQueryWrapper<SapData> wrapper = new LambdaQueryWrapper();
        wrapper.in(SapData::getId, Ids);
        wrapper.eq(SapData::getIsEnable,1);
        return baseMapper.selectList(wrapper);
    }

    @Override
    public List<String> getOrderNos(List<Long> Ids) {
        List<String> orderNos = sapDataMapper.getOrderNos(Ids);
        return orderNos;
    }

}
